const Invitation = require('../models').Invitation

module.exports = function (router) {
  // 生成邀请码
  router.post('/invitation', function * () {
    if (!this.config.invitation.enable) this.throw('本站已禁用邀请注册功能。')

    let {_id: inviter, username} = this.state.user
    if (this.config.invitation.limited &&
        !this.config.invitation.user[username]) this.throw('没有邀请权限。')

    let code = this.utils.random(6)
    let invitation = yield Invitation.findOne({code}).exec()

    while (invitation) {
      code = this.utils.random(6)
      invitation = yield Invitation.findOne({code}).exec()
    }

    invitation = Invitation.create({code, inviter})
    this.body = this.apiSuccess({invitation})
  })

  // 获取邀请码列表
  router.get('/invitation', function * () {
    let {_id: inviter} = this.state.user

    let invitations = yield Invitation.find({inviter}).exec()
    this.body = this.apiSuccess({invitations})
  })

  // 删除要求码
  router.delete('/invitation/:invitationId', function * () {
    this.checkParams('invitationId').notEmpty('缺少id')
    if (this.errors) this.throwError()

    let {invitationId} = this.params
    let invitation = yield Invitation.findById(invitationId).exec()
    if (invitation) yield invitation.remove()

    this.body = this.apiSuccess()
  })
}
